package com.example.ll_video.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.ll_video.MyApplication;
import com.example.ll_video.R;
import com.example.ll_video.adapter.MainFragmentAdapter;
import com.example.ll_video.bean.OtherInfo;
import com.example.ll_video.bean.ResultData;
import com.example.ll_video.bean.UserInfo;
import com.example.ll_video.constant.Constant;
import com.example.ll_video.fragment.HomeFragment;
import com.example.ll_video.fragment.MiddleFragment;
import com.example.ll_video.fragment.MiddleRightFragment;
import com.example.ll_video.fragment.RightFragment;
import com.example.ll_video.permission.ZbPermission;
import com.example.ll_video.service.UpdateService;
import com.example.ll_video.utils.HttpUtils;
import com.example.ll_video.utils.JsonUtil;
import com.example.ll_video.utils.SPUtils;
import com.example.ll_video.utils.ToastUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.qmuiteam.qmui.widget.QMUIViewPager;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewMainActivity extends AppCompatActivity {
    @BindView(R.id.view_pager)
    QMUIViewPager viewPager;
    @BindView(R.id.bottom_nav)
    BottomNavigationView bottomNav;
    MainFragmentAdapter pagerAdapter;
    List<Fragment> fragmentList = new ArrayList<>();

    HomeFragment homeFragment;
    MiddleFragment midleFragment;
    MiddleRightFragment middleRightFragment;
    RightFragment rightFragment;
    public static String SERVICE_BC = "main_broadcast";
    IntentFilter intentFilter;
    MyReceiver myReceiver;
    /*  @BindView(R.id.main_swipe_view)
      SmartSwipeWrapper mainSwipeView;*/
    @BindView(R.id.iv_user_avatar)
    QMUIRadiusImageView2 ivUserAvatar;
    @BindView(R.id.ll_user_info)
    LinearLayout llUserInfo;
    @BindView(R.id.iv_user_avatar2)
    QMUIRadiusImageView2 ivUserAvatar2;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.ll_shouye)
    LinearLayout llShouye;
    @BindView(R.id.ll_chongzhi)
    LinearLayout llChongzhi;
    @BindView(R.id.ll_shoucang)
    LinearLayout llShoucang;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    @BindView(R.id.ll_mine)
    LinearLayout llMine;
    @BindView(R.id.tv_main_title)
    TextView tvMainTitle;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_main_activity_math);
        ButterKnife.bind(this);
        QMUIStatusBarHelper.isFullScreen(this);
       /* mainSwipeView
                .addConsumer(new DrawerConsumer())    //抽屉效果
                //可以设置横向(左右两侧)的抽屉为同一个view
                //也可以为不同方向分别设置不同的view
                .setHorizontalDrawerView(llMine)
                .setScrimColor(0x2F000000) //设置遮罩的颜色
                .setShadowColor(0x80000000)    //设置边缘的阴影颜色
        ;*/

        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.FOREGROUND_SERVICE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.INSTALL_PACKAGES,
                    Manifest.permission.DELETE_PACKAGES,
                    Manifest.permission.READ_EXTERNAL_STORAGE};
        } else {
            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.INSTALL_PACKAGES,
                    Manifest.permission.DELETE_PACKAGES,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            };
        }
        ZbPermission.with(NewMainActivity.this)
                .addRequestCode(100)
                .permissions(permissions)
                .request(new ZbPermission.ZbPermissionCallback() {

                    @Override
                    public void permissionSuccess(int requestCode) {
                    }

                    @Override
                    public void permissionFail(int requestCode) {
                        finish();
                    }
                });

        Intent intent = new Intent(this, UpdateService.class);
        startService(intent);
        viewPager.setSwipeable(false);
        homeFragment = new HomeFragment();
        midleFragment = new MiddleFragment();
        middleRightFragment = new MiddleRightFragment();
        rightFragment = new RightFragment();
        fragmentList.add(homeFragment);
        fragmentList.add(midleFragment);
        fragmentList.add(middleRightFragment);
        fragmentList.add(rightFragment);
        pagerAdapter = new MainFragmentAdapter(getSupportFragmentManager(), 0, fragmentList);
        viewPager.setAdapter(pagerAdapter);
        intentFilter = new IntentFilter(SERVICE_BC);
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, intentFilter);

        bottomNav.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.menu_home:
                    tvMainTitle.setText("首页");
                    viewPager.setCurrentItem(0);
                    break;
                case R.id.menu_middle_left:
                    tvMainTitle.setText("黑科技");
                    viewPager.setCurrentItem(1);
                    break;
                case R.id.menu_middle_right:
                    tvMainTitle.setText("视频");
                    viewPager.setCurrentItem(2);
                    break;
                case R.id.menu_right:
                    tvMainTitle.setText("我的");
                    viewPager.setCurrentItem(3);
                    break;
            }
            return true;
        });

        setUserInfo();
        getOtherInfo();
    }


    private void setUserInfo() {
        UserInfo userInfo1 = null;
        final String sUserInfo = (String) SPUtils.get(this, "userInfo", "");
        if (!TextUtils.isEmpty(sUserInfo)) {
            JSONObject jsonObject = JSON.parseObject(sUserInfo);
            userInfo1 = JsonUtil.jsonToObject(jsonObject.getString("userinfo"), UserInfo.class);
            MyApplication.getInstance().setUserInfo(userInfo1);
        }

//        ivUserAvatar.setImageBitmap(Base64Bitmap.stringToBitmap(userInfo.getAvatar()));
//        ivUserAvatar2.setImageBitmap(Base64Bitmap.stringtoBitmap(userInfo.getAvatar()));
        if (userInfo1 != null && !TextUtils.isEmpty(userInfo1.getUsername())) {
            tvUserName.setText(userInfo1.getUsername());
        } else {
            tvUserName.setText("未登录");
            tvUserName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(NewMainActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
        }

    }


    @OnClick({R.id.ll_user_info})
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.ll_user_info:
                break;
            case R.id.ll_shouye:
                break;
            case R.id.ll_setting:
                intent.setClass(NewMainActivity.this, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_chongzhi:
                intent.setClass(NewMainActivity.this, PayActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_shoucang:
                intent.setClass(NewMainActivity.this, AboutActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void getOtherInfo() {
        HttpUtils.get(Constant.OTHER_INFO, new HttpUtils.HttpCallBack() {
            @Override
            public void onSuccess(ResultData resultData) {
                if (resultData.getCode() == 1) {
                    List<OtherInfo> list = JsonUtil.jsonToList(resultData.getData(), OtherInfo.class);
                    MyApplication.getInstance().setOtherInfo(list.get(0));
                }
            }

            @Override
            public void onFail(String error) {
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void install(String apkFile) {
        ToastUtils.showTextToast(getApplicationContext(), "下载完成");
        if (apkFile != null) {
            Uri uri = Uri.fromFile(new File(apkFile));
            Intent intent = new Intent(Intent.ACTION_VIEW);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(NewMainActivity.this, "com.example.ll_video.fileprovider",
                        new File(apkFile));
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            }
            startActivity(intent);
        }
       /* ToastUtils.showTextToast(getApplicationContext(), "下载完成");
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "install", "-i", "com.example.ll_video", "-r", apkFile).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {

        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {

            }
            if (process != null) {
                process.destroy();
            }
        }
        Log.i("qin>>", errorMsg.toString());
        Toast.makeText(NewMainActivity.this, errorMsg.toString() + "  " + successMsg, Toast.LENGTH_LONG).show();
        //如果含有“success”单词则认为安装成功
        return successMsg.toString().equalsIgnoreCase("success");*/

    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String flag = intent.getStringExtra("flag");
            assert flag != null;
            switch (flag) {
                case "installApp":
                    String filePath = intent.getStringExtra("filePath");
                    install(filePath);
                   /* if (install(filePath)) {
                        ToastUtils.showTextToast(context, "安装成功");
                    } else {
                        ToastUtils.showTextToast(context, "安装失败");
                    }*/
                    break;
            }
        }
    }
}
